<!--
 * @Descripttion:
 * @Author: armin
 * @Date: 2021-07-20 09:23:48
 * @LastEditors: armin
 * @LastEditTime: 2022-04-11 15:12:08
-->
<template>
  <div class="create-post-page container">
    <h4>{{isEditMode ? '编辑文章' : '新建文章'}}</h4>
    <uploader
      action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      :beforeUpload="uploadCheck"
      :uploaded="uploadedData"
      @file-uploaded="handleFileUploaded"
    >
    <h2>点击上传图片，支持 JPG 或者 PNG 格式</h2>
    <template #loading>
      <div class="d-flex">
        <div class="spinner-border text-secondary" role="status">
          <span class="sr-only"></span>
        </div>
        <h2>正在上传中，请稍后</h2>
      </div>
    </template>
    <template #uploaded="dataProps">
      <img :src="dataProps.uploadedData.data.url" width="500" />
    </template>
    </uploader>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <editor ref="editorRef" v-model="contentVal" :options="editorOptions" @blur="checkEditor" :class="{'is-invalid': !editorStatus.isValid}"></editor>
        <span v-if="!editorStatus.isValid" class="invalid-feedback mt-1">{{editorStatus.message}}</span>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import ValidateForm from '@/components/ValidateForm.vue'
import ValidateInput, { RulesProp } from '@/components/ValidateInput.vue'
import { useStore } from 'vuex'
import EasyMDE, { Options } from 'easymde'
import { IGlobalDataProps, PostProps, ResponseType, ImageProps } from '@/store'
import { defineComponent, onMounted, ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Uploader from '@/components/Uploader.vue'
import Editor from '../components/Editor.vue'
import createMessage from '@/components/createMessage'
import { beforeUploadCheck } from '@/help'
interface EditorInstance {
  clear: () => void;
  getMDEInstance: () => EasyMDE | null;
}
export default defineComponent({
  components: { ValidateForm, ValidateInput, Uploader, Editor },
  setup () {
    const store = useStore<IGlobalDataProps>()
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const textArea = ref<null | HTMLTextAreaElement>()
    const editorRef = ref<null | EditorInstance>()
    let imageId = ''
    const editorOptions: Options = {
      spellChecker: false
    }
    const titleVal = ref('')
    const editorStatus = reactive({
      isValid: true,
      message: ''
    })
    const uploadedData = ref()
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const checkEditor = () => {
      if (contentVal.value.trim() === '') {
        editorStatus.isValid = false
        editorStatus.message = '文章详情不能为空'
      } else {
        editorStatus.isValid = true
        editorStatus.message = ''
      }
    }
    const contentVal = ref('')
    onMounted(() => {
      if (editorRef.value) {
        console.log(editorRef.value.getMDEInstance())
      }
      if (isEditMode) {
        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          const currentPost = rawData.data
          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }
    // 提交
    const onFormSubmit = (result: boolean) => {
      checkEditor()
      if (result && editorStatus.isValid) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: newPost
          } : newPost
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功，2秒后跳转到文章', 'success', 2000)
            setTimeout(() => {
              router.push({ name: 'column', params: { id: column } })
            }, 2000)
          })
        }
      }
    }
    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
      const { passed, error } = result
      if (error === 'format') {
        createMessage('上传图片只能是 JPG/PNG 格式！', 'error', 2000)
      }
      if (error === 'size') {
        createMessage('上传图片不能超过 1Mb', 'error', 2000)
      }
      return passed
    }
    return {
      titleVal,
      titleRules,
      contentVal,
      uploadedData,
      isEditMode,
      textArea,
      editorOptions,
      editorRef,
      editorStatus,
      checkEditor,
      onFormSubmit,
      uploadCheck,
      handleFileUploaded
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
